package com.shangxia.dog.api;


import com.shangxia.dog.base.entity.Admin;
import com.shangxia.dog.base.service.IAdminService;
import com.shangxia.dog.commom.vo.ResultVO;
import com.shangxia.dog.vo.LoginAdmin;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author shangxia
 * @since 2022-01-16
 */
@Api(tags = "LoginController")
@RestController
@RequestMapping("")
public class LoginController {

    @Autowired
    private IAdminService adminService;

    @ApiOperation(value = "登录之后返回token")
    @PostMapping("/login")
    public ResultVO<String> login(@RequestBody LoginAdmin loginAdmin, HttpServletRequest request) {
        return adminService.login(loginAdmin.getUsername(), loginAdmin.getPassword(), loginAdmin.getCode(), request);
    }

    @ApiOperation(value = "获取登录用户信息")
    @GetMapping("/getAdmin")
    public ResultVO<Admin> getAdminInfo(Principal principal) {
        if (principal == null) {
            return ResultVO.error("未登录");
        }
        Admin admin = adminService.getRolesById(principal.getName());
        if (null == admin) {
            return ResultVO.error("用户不存在");
        }
        admin.setPassword(null);
        admin.setRoles(adminService.getRolesById(admin.getId()));
        return ResultVO.success(admin);
    }


    @ApiOperation(value = "退出登录")
    @PostMapping("/loginOut")
    public ResultVO<String> login() {
        //也可以设置token失效
        return ResultVO.success("注销成功");
    }

}
